import { Router } from 'express'
import { body, query } from 'express-validator'
import { asyncHandler } from '../middleware/errorHandler'
import { handleValidationErrors, validatePagination } from '../middleware/validation'
import { authenticate, AuthRequest } from '../middleware/auth'
import { HonorService } from '../services/honorService'

const router = Router()
const honorService = new HonorService()

// All routes require authentication
router.use(authenticate)

// Get honors
router.get('/', validatePagination, asyncHandler(async (req: AuthRequest, res) => {
  const { page, limit, memberId, honorType } = req.query as any
  const honors = await honorService.getHonors({ page, limit, memberId, honorType })
  
  res.json({
    success: true,
    data: honors,
  })
}))

// Create honor
router.post('/', [
  body('title').notEmpty().withMessage('Honor title is required'),
  body('memberId').isInt().withMessage('Member ID must be an integer'),
  body('honorType').optional().isIn(['ACHIEVEMENT', 'AWARD', 'RECOGNITION']).withMessage('Invalid honor type'),
], handleValidationErrors, asyncHandler(async (req: AuthRequest, res) => {
  const honorData = req.body
  const honor = await honorService.createHonor(honorData)
  
  res.status(201).json({
    success: true,
    data: honor,
  })
}))

// Get honor by ID
router.get('/:id', asyncHandler(async (req: AuthRequest, res) => {
  const { id } = req.params
  const honor = await honorService.getHonorById(parseInt(id))
  
  if (!honor) {
    throw new Error('Honor not found')
  }
  
  res.json({
    success: true,
    data: honor,
  })
}))

// Update honor
router.put('/:id', [
  body('title').optional().notEmpty().withMessage('Honor title cannot be empty'),
  body('honorType').optional().isIn(['ACHIEVEMENT', 'AWARD', 'RECOGNITION']).withMessage('Invalid honor type'),
], handleValidationErrors, asyncHandler(async (req: AuthRequest, res) => {
  const { id } = req.params
  const updateData = req.body
  
  const honor = await honorService.updateHonor(parseInt(id), updateData)
  
  res.json({
    success: true,
    data: honor,
  })
}))

// Delete honor
router.delete('/:id', asyncHandler(async (req: AuthRequest, res) => {
  const { id } = req.params
  await honorService.deleteHonor(parseInt(id))
  
  res.json({
    success: true,
    message: 'Honor deleted successfully',
  })
}))

// Get honors by member
router.get('/member/:memberId', validatePagination, asyncHandler(async (req: AuthRequest, res) => {
  const { memberId } = req.params
  const { page, limit } = req.query as any
  
  const honors = await honorService.getHonorsByMember(parseInt(memberId), { page, limit })
  
  res.json({
    success: true,
    data: honors,
  })
}))

// Get honor statistics
router.get('/statistics/summary', asyncHandler(async (req: AuthRequest, res) => {
  const stats = await honorService.getHonorStatistics()
  
  res.json({
    success: true,
    data: stats,
  })
}))

export { router as honorRouter }